/**
 * Read HTTP request
 */

#include <stdlib.h>
#include <string.h>
#include <fcntl.h>

#include "nweb.h"
#include "nweb_log.h"

/* Reception */
request_rec* read_request(int fd, int hit) {
    request_rec *r;
    long i, ret;
    char *brkt;
    static char buffer[BUFSIZE+1]; /* static so zero filled */
    char *sep = " \0"; /* http use space as seperator */

    r = malloc(sizeof(request_rec));

    ret =read(fd,buffer,BUFSIZE); 	/* read Web request in one go */

    /* error checking */
    if(ret == 0 || ret == -1) {	/* read failure stop now */
            nweb_log(SORRY,"failed to read browser request","",fd);
    }
    if(ret > 0 && ret < BUFSIZE)	/* return code is valid chars */
            buffer[ret]=0;		/* terminate the buffer */
    else buffer[0]=0;

    for(i=0;i<ret;i++)	/* remove CF and LF characters */
            if(buffer[i] == '\r' || buffer[i] == '\n')
                    buffer[i]='*';
    nweb_log(LOG,"request",buffer,hit);

    /* construct request_rec */
    r->buffer = malloc(BUFSIZE+1);
    strncpy(r->buffer, buffer, strlen(buffer));
    r->fd = fd;
    r->hit = hit;
    r->method = strtok_r(buffer, " ", &brkt); /* extract the moethod */
    r->unparsed_uri = strtok_r(NULL, " ", &brkt);

    return r;
}